<template>
  <div class="app-container">

    <!-- 功能操作按钮 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <!-- 搜索栏 -->
        <el-form :inline="true" :model="searchForm" class="mb-20">
          <el-form-item label="关键词">
            <el-input v-model="searchForm.keyword" placeholder="输入关键词" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12" class="text-right mb-20" align="right">
        <el-button type="primary" @click="handleAddTopic">新增课题</el-button>
      </el-col>
    </el-row>

    <!-- 课题表格 -->
    <el-table :data="topicList" border style="width: 100%">
      <el-table-column label="序号" width="80" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="topicName" label="课题名称" show-overflow-tooltip align="center" />
      <el-table-column prop="createTime" label="创建时间" width="160" align="center">
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="创建人" width="120" align="center">
        <template #default="scope">
          {{ UserNickNames[scope.$index] }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" @click="handleEditTopic(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDeleteTopic(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="mt-20"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      :current-page="currentPage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
      <el-form ref="topicForm" :model="topicForm" :rules="rules" label-width="120px">
        <el-form-item label="课题名称" prop="topicName">
          <el-input v-model="topicForm.topicName" placeholder="请输入课题名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getList, createTopic, deleteTopic } from '@/api/topic' // 后期替换为真实接口
import moment from 'moment'

export default {
  name: 'TopicManage',
  data() {
    return {
      topicList: [], // 课题列表
      UserNickNames: [], // 用户昵称列表
      total: 0, // 总记录数
      pageSize: 10, // 每页数量
      currentPage: 1, // 当前页码
      searchForm: {
        keyword: ''
      },
      dialogVisible: false, // 弹窗显示状态
      dialogTitle: '新增课题', // 弹窗标题
      dialogType: 'add', // add/edit
      topicForm: {
        topicId: null,
        topicName: ''
      },
      rules: {
        topicName: [
          { required: true, message: '课题名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取课题列表
    async fetchData() {
      try {
        const res = await getList({
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        })
        this.topicList = res.topicPage.records
        this.total = res.topicPage.total
        this.UserNickNames = res.UserNickNames
      } catch (error) {
        this.$message.error('获取课题列表失败')
      }
    },
    // 时间格式化
    formatTime(time) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        topicName: '',
        createUserId: null
      }
      this.currentPage = 1
      this.fetchData()
    },
    // 新增课题弹窗
    handleAddTopic() {
      this.dialogType = 'add'
      this.dialogTitle = '新增课题'
      this.topicForm = {
        topicId: null,
        topicName: '',
        createUserId: null,
        createTime: null
      }
      this.dialogVisible = true
    },
    // 编辑课题
    handleEditTopic(row) {
      this.dialogType = 'edit'
      this.dialogTitle = '编辑课题'
      this.topicForm = row
      this.dialogVisible = true
    },
    // 提交表单
    handleSubmit() {
      this.$refs['topicForm'].validate(async valid => {
        if (valid) {
          if (this.dialogType === 'add') {
            try {
              await createTopic(this.topicForm)
              this.$message.success('新增成功')
              this.dialogVisible = false
              this.fetchData()
            } catch (error) {
              this.$message.error('新增失败')
            }
          } else {
            try {
              await createTopic(this.topicForm)
              this.$message.success('更新成功')
              this.dialogVisible = false
              this.fetchData()
            } catch (error) {
              this.$message.error('更新失败')
            }
          }
        }
      })
    },
    // 删除课题
    handleDeleteTopic(row) {
      this.$confirm('确定删除该课题?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deleteTopic({ topicId: row.topicId })
          this.$message.success('删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}

.mt-20 {
  margin-top: 20px;
}
</style>
